<template>
  <div class="user-login-page">

    <!-- 顶部选择语言 -->
    <div class="user-header">
      <div class="user-header-lang">
        <span @click="selectLang">选择语言</span>
        <van-icon name="arrow-down" />
      </div>
      <div @click="setLang">需要帮助</div>
    </div>

    <!-- log -->
    <div class="user-log">
      <van-image width="50" height="50" :src="require('@/assets/images/login/logo-mi2.png')" />
      <div>让每个人都能享受科技带来的乐趣</div>
    </div>

    <!-- 登录表单 -->
    <div class="login-form">
      <span class="login-form-title">小米账号{{ $route.params.id }}</span>
      <van-form @submit="onSubmit">
        <van-field v-if="$route.params.id === '注册'" v-model.trim="nikename" name="nikename" placeholder="请输入昵称" :rules="[
          { required: true, message: '请填写昵称' }
        ]" />
        <van-field v-model.trim="useremail" name="email" placeholder="请输入Email账号" :rules="[
          { required: true, message: '请填写Email账号' },
          { pattern, message: '请输入正确的邮箱' }
        ]" />
        <van-field v-model.trim="password" type="password" name="password" placeholder="密码" :rules="[{ required: true, message: '请填写密码' },
        { pattern: patternPassword, message: '密码长度为6-20为 且只能包含字母数字和下划线' }
        ]" />

        <van-field name="checkbox">
          <template #input>
            <van-checkbox class="tick-protocol" v-model="checked" icon-size="15px" shape="square">
              已阅读并同意小米账号
              <router-link to="#">用户协议</router-link>
              和
              <router-link to="#">隐私政策</router-link>
            </van-checkbox>
          </template>
        </van-field>



        <div style="margin: 16px;">
          <van-button round block type="info" native-type="submit">提交</van-button>
        </div>
        <label v-if="$route.params.id === '登陆'" class="toLogin">
          没有账号？
          <router-link :to="{ name: 'user_login', params: { id: '注册' } }">立即注册</router-link>
        </label>
      </van-form>
    </div>

    <!-- 弹出层 -->
    <van-popup v-model:show="showLangPopup" position="top" closeable :style="{ height: '28%' }">
      <h4 class="selectLang">选择语言</h4>
      <div class="selectLang" @click="setLang">中文（简体）</div>
      <div class="selectLang" @click="setLang">English</div>
    </van-popup>
  </div>
</template>


<script>
import { useRoute,useRouter } from "vue-router";//引入路由组件
import { ref } from "vue";
import { userLogin, userRegister } from '@/api/user'
import { getCurrentInstance } from 'vue'
import { useStore } from 'vuex'
export default {
  setup() {
    const store = useStore()//vuex
    const route = useRoute()//路由信息
    const router =useRouter()//路由
    // console.log(route.params); //   打印 params 的参数

    // 选择语言弹窗逻辑
    const showLangPopup = ref(false)//定义控制显示语言弹窗
    const selectLang = () => {
      showLangPopup.value = ref(true)
      // 让这个弹窗显示
    }

    const instance = getCurrentInstance()
    const _this = instance.appContext.config.globalProperties
    const setLang = ()=>{
      _this.$toast('开发中，敬请期待')
    }
    // 获取this全局变量

    // 登录校验逻辑
    const nikename = ref('')
    const useremail = ref('')
    const password = ref('')
    const checked = ref(false)
    // 邮箱的正则校验
    const pattern = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/
    // 密码正则校验
    const patternPassword = /^(\w){6,20}$/
    const onSubmit = async (value) => {
      // 如果未勾选提示
      if (!value.checkbox) return _this.$toast.fail('请确认勾选用产协议和隐私政策')
      _this.$toast.loading('登陆中...')
      // 区分是登陆还是注册
      if (route.params.id === '登陆') {
        try {
          // 登陆逻辑
          const res = await userLogin({
            email: useremail.value,
            password: password.value
          })
          // vuex同步
          store.commit('user/setUserinfo', res.data)
          _this.$toast.success('登陆成功')
          //获取用户信息
          // store.dispatch('user/getUserInfo')
          router.go(-1)
        } catch (error) {
          console.log(error);
          _this.$toast.fail('登陆失败，请检查账号密码或稍后重试')
        }
      } else {
        try {
          // 注册并登陆逻辑
          const res = await userRegister({
            name: nikename.value,
            email: useremail.value,
            password: password.value,
            c_password: password.value
          })
          store.commit('user/setUserinfo', res.data)
          //获取用户信息
          // store.dispatch('user/getUserInfo')
          
          _this.$toast.success('注册并登陆成功')
          router.go(-1)
        } catch (err) {
          _this.$toast.fail('该账户以注册')
          console.log(err);
        }
      }


    }
    return {
      showLangPopup,
      selectLang,
      setLang,
      nikename,
      useremail,
      password,
      onSubmit,
      checked,
      pattern,
      patternPassword
    }
  },
};

</script>

<style lang="scss" scoped>
.user-login-page {
  .user-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 10px;
    color: #999;
    height: 76px;
    padding: 0 25px;
  }

  ::v-deep .van-popup {
    .selectLang {
      font-size: 4.26667vw;
      margin: 30px 0 30px 20px;
    }
  }

  .user-log {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    margin-top: 30px;

    div {
      margin-top: 20px;
      font-size: 14px;
      color: #999;
    }
  }

  .login-form {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;

    .login-form-title {
      font-weight: 700;
      font-size: 18px;
      align-self: flex-start;
      padding: 50px 0 10px 16px;
    }

    // ::v-deep #van-field-1-input,::v-deep #van-field-2-input{
    ::v-deep [type="password"].van-field__control,
    ::v-deep [type="text"].van-field__control {
      height: 50px;
      width: 325px;
      padding-left: 20px;
      transition: border 0.3s linear;
      // box-sizing: border-box;
      border-radius: 30px;
      background-color: #f5f5f5;
      border: 2px solid #f5f5f5;

      &:hover {
        // padding-left: 18px;
        border: 2px solid #ff2300;
      }

    }

    ::v-deep .van-button {
      height: 50px;
      width: 326px;
      background-color: #ff6700;
      border: none;
      font-size: 14px;
      color: #f5f5f5;
    }

    .tick-protocol {
      font-size: 15px;
      justify-content: center;

    }

    .toLogin {
      font-size: 14px;
      color: #0f86ff;

      a {
        color: #ff6700;
      }
    }
  }
}
</style>